package api

import (
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"net/http"
	"todo-list/constants"
	"todo-list/service"
	"todo-list/types"
	"todo-list/utils/responses"
)

func RegisterHandler() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		var req types.UserRegisterReq
		err := ctx.ShouldBindJSON(&req)
		if err != nil {
			logrus.Errorln(err.Error())
			ctx.JSON(http.StatusInternalServerError, responses.RespError(err, constants.CodeInvalidParams))
			return
		}
		l := service.GetUserSrv()
		err = l.Register(ctx.Request.Context(), &req)
		if err != nil {
			logrus.Errorln(err.Error())
			ctx.JSON(http.StatusInternalServerError, responses.RespError(err, constants.CodeRegisterFail))
			return
		}
		ctx.JSON(http.StatusOK, responses.RespSuccess())
	}
}

func LoginHandler() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		var req types.UserLoginReq
		err := ctx.ShouldBindJSON(&req)
		if err != nil {
			logrus.Errorln(err.Error())
			ctx.JSON(http.StatusInternalServerError, responses.RespError(err, constants.CodeInvalidParams))
			return
		}
		l := service.GetUserSrv()
		data, err := l.Login(ctx, &req)
		if err != nil {
			logrus.Errorln(err.Error())
			ctx.JSON(http.StatusInternalServerError, responses.RespError(err, constants.CodeLoginFail))
			return
		}
		ctx.JSON(http.StatusOK, responses.RespSuccessWithData(*data))
	}
}

func LogoutHandler() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		token := getToken(ctx)
		l := service.GetUserSrv()
		err := l.Logout(token)
		if err != nil {
			logrus.Errorln(err.Error())
			ctx.JSON(http.StatusInternalServerError, responses.RespError(err, constants.CodeLogoutFail))
			return
		}
		ctx.Header("Authorization", "")
		ctx.JSON(http.StatusOK, responses.RespSuccess())
	}
}
